package com.example.android.commitcontent.ime.fragments;


import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.example.android.commitcontent.ime.R;
import com.example.android.commitcontent.ime.beans.HanZiCharacter;
import com.example.android.commitcontent.ime.beans.HanZiWord;
import com.example.android.commitcontent.ime.beans.WordsUploadBody;
import com.example.android.commitcontent.ime.cores.adapters.BaseRecyclerViewAdapter;
import com.example.android.commitcontent.ime.cores.base.BaseFragment;
import com.example.android.commitcontent.ime.cores.utils.MacAddressHelper;
import com.example.android.commitcontent.ime.cores.utils.ToastHelper;
import com.example.android.commitcontent.ime.database.hanzi.HanZiStatisticsDataBaseHelper;
import com.example.android.commitcontent.ime.database.managers.HanZiWordDictManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import cn.pluss.baselibrary.http.HttpRequest;
import cn.pluss.baselibrary.http.callback.SimpleHttpCallBack;
import cn.pluss.baselibrary.http.exception.ApiException;

/**
 * A simple {@link Fragment} subclass.
 */
public class HanZiStatisticsManageFragment extends BaseFragment {

    public static final int TYPE_LETTERS = 1;
    public static final int TYPE_WORDS = 2;
    private static final String ARG_TYPE = "type";
    private HanZiWordDictManager mHanZiWordDictManager;
    private int mType;

    public static HanZiStatisticsManageFragment newInstance(int type) {
        HanZiStatisticsManageFragment fragment = new HanZiStatisticsManageFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = getArguments().getInt(ARG_TYPE);
        mHanZiWordDictManager = HanZiWordDictManager.instance(getContext());
    }

    @BindView(R.id.ll_empty_view)
    LinearLayout mLlEmptyView;
    @BindView(R.id.sr_refresh)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.rv_words)
    RecyclerView mRvWord;
    List<HanZiCharacter> mHanZiCharacterList = new ArrayList<>();
    List<HanZiWord> mHanZiWordList = new ArrayList<>();

    private HanZiStatisticsDataBaseHelper mHanZiStatisticsDataBaseHelper;
    private BaseRecyclerViewAdapter<HanZiCharacter> mLetterAdapter;
    private BaseRecyclerViewAdapter<HanZiWord> mWordsAdapter;

    public HanZiStatisticsManageFragment() {
    }

    @Override
    protected int setLayoutRes() {
        return R.layout.fragment_han_zi_statistics_manage;
    }

    @Override
    protected void initView() {
        if (mType == TYPE_LETTERS) {
            mLetterAdapter = new BaseRecyclerViewAdapter<HanZiCharacter>(getContext(), R.layout.item_hanzi_statistics_manage, mHanZiCharacterList) {
                @Override
                protected void onBindData(@NonNull HanZiCharacter data, @NonNull Holder holder, int position) {
                    holder.text(R.id.tv_hanzi, data.hanzi);
                    holder.text(R.id.tv_pinyin, data.pinyin);
                    holder.text(R.id.tv_count, String.format("%s次", data.repeatCount));
                }
            };
            mRvWord.setAdapter(mLetterAdapter);
        } else {
            mWordsAdapter = new BaseRecyclerViewAdapter<HanZiWord>(getContext(), R.layout.item_hanzi_statistics_manage, mHanZiWordList) {
                @Override
                protected void onBindData(@NonNull HanZiWord data, @NonNull Holder holder, int position) {
                    holder.text(R.id.tv_hanzi, data.hanziWord);
                    holder.text(R.id.tv_pinyin, data.pinyin);
                    holder.text(R.id.tv_count, String.format("%s次", data.repeatCount));
                }
            };
            mRvWord.setAdapter(mWordsAdapter);
        }
        mRvWord.setLayoutManager(new LinearLayoutManager(getContext()));
        mRefreshLayout.setOnRefreshListener(this::getData);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void lazyLoadData() {
        mRefreshLayout.setRefreshing(true);
        getData();
    }

    private void getData() {
        mHanZiStatisticsDataBaseHelper = HanZiStatisticsDataBaseHelper.intance(getContext());
        boolean isEmpty = false;
        if (mType == TYPE_LETTERS) {
            mHanZiCharacterList.clear();
            mHanZiCharacterList.addAll(mHanZiStatisticsDataBaseHelper.getHanZiList());
            Collections.sort(mHanZiCharacterList, new Comparator<HanZiCharacter>() {
                @Override
                public int compare(HanZiCharacter hanZi1, HanZiCharacter hanZi2) {
                    return hanZi2.repeatCount - hanZi1.repeatCount;
                }
            });
            isEmpty = mHanZiCharacterList.size() == 0;
            mLetterAdapter.notifyDataSetChanged();
        } else {
            mHanZiWordList.clear();
            mHanZiWordList.addAll(mHanZiStatisticsDataBaseHelper.getHanZiWordList());
            Collections.sort(mHanZiWordList, new Comparator<HanZiWord>() {
                @Override
                public int compare(HanZiWord ziWord1, HanZiWord ziWord2) {
                    return ziWord2.repeatCount - ziWord1.repeatCount;
                }
            });
            isEmpty = mHanZiWordList.size() == 0;
            mWordsAdapter.notifyDataSetChanged();
        }
        mLlEmptyView.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
        mRefreshLayout.setRefreshing(false);
    }

    /**
     * 更新字库
     */
    public void updateCharacterDict() {

    }

    /**
     * 上传字库
     */
    public void uploadCharacterDict() {
    }

    /**
     * 更新词库
     */
    public void updateWordDict() {
        HttpRequest.post("queryLexicon")
                .bindLifecycle(this)
                .executeArray(HanZiWord.class, new SimpleHttpCallBack<HanZiWord>() {
                    @Override
                    public void onStart() {
                        showLoadingDialog("词库同步中", "从服务器获取信息");
                    }

                    @Override
                    public void onSuccess(ArrayList<HanZiWord> list) {
                        showLoadingDialog("词库同步中", "数据同步中，请勿退出应用");
                        mHanZiWordDictManager.updateWordsDict(list, new HanZiWordDictManager.OnWordsUpdateSuccessListener() {
                            @Override
                            public void onWordsUpdateSuccess() {
                                ToastHelper.show(getContext(), "本地词库更新完成");
                                dismissLoadingDialog();
                                getData();
                            }
                        });
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissLoadingDialog();
                        ToastHelper.show(getContext(), e.getMessage());
                    }

                    @Override
                    public void onCompleted() {
                    }
                });
    }

    /**
     * 上传词库
     */
    public void uploadWordDict() {
        HttpRequest.post("saveLexicon")
                .bindLifecycle(this)
                .execute(new WordsUploadBody(getContext(),mHanZiWordList), new SimpleHttpCallBack<String>() {

                    @Override
                    public void onStart() {
                        showLoadingDialog("上传中", "正在上传词库...");
                    }

                    @Override
                    public void onSuccess(String string) {
                        ToastHelper.show(getContext(), "上传成功");
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissLoadingDialog();
                        ToastHelper.show(getContext(), e.getMessage());
                    }

                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }
                });
    }

}
